<!-- 农产品管理 -->
<template>
  <div>
    <CommonSearch @search="query" @reset="reset">
      <el-col :span="8">
        <el-form-item label="农产品名称">
          <el-input
            v-model="queryParams.condition.title"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="农产品类型">
          <QueryCategoryTree
            v-model="queryParams.condition.produceType"
            cacheValue="PRODUCE_TYPE"
            :payload="{ dictType: 'PRODUCE_TYPE' }"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.condition.searchTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%; height: 33px"
            @change="(date) => timeChange(date, queryParams.condition)"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="上架状态">
          <DictSelect
            v-model="queryParams.condition.pushStatus"
            :defaultOptions="options.pushStatus"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="是否推荐">
          <DictSelect
            v-model="queryParams.condition.recommend"
            :defaultOptions="options.recommend"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </CommonSearch>

    <el-row class="cardMiniBar">
      <el-col :span="24">
        <div class="fr">
          <el-button type="primary" @click="add" size="small">新增</el-button>
          <el-button @click="batchPublish" size="small">批量上架</el-button>
          <el-button @click="revokeBatchPublish" size="small"
            >批量下架</el-button
          >
          <el-button @click="batchRecommended" size="small">批量推荐</el-button>
          <el-button @click="revokeBatchRecommended" size="small"
            >批量取消推荐</el-button
          >
          <el-button @click="onExport" size="small">导出</el-button>
        </div>
      </el-col>
    </el-row>

    <div class="cardBody">
      <edu-table
        ref="mainTable"
        :data="tableList"
        :pageSize="queryParams.pageSize"
        :pageNum="queryParams.pageNum"
        :total="queryParams.total"
        @page-change="handleCurrentChange"
        :order="true"
        :selection="true"
      >
        <el-table-column label="农产品图" prop="image">
          <template slot-scope="scope">
            <el-image
              :src="`/nongmao/nb-as/1.0.1/FileService/previewFile?fileId=${scope.row.image}`"
              style="width: 100px; height: 100px"
              class="banner"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="农产品名称" prop="title" />
        <el-table-column label="商户名称" prop="providerName" />
        <el-table-column label="农产品类型" prop="produceTypeName" />
        <el-table-column label="价格" prop="price" :formatter="rounding" />
        <el-table-column label="创建时间" prop="pushTime" width="160" />
        <el-table-column label="是否推荐" prop="recommend">
          <template slot-scope="scope">
            {{ renderOption(scope.row.recommend, "recommend") }}
          </template>
        </el-table-column>
        <el-table-column label="上架状态" prop="pushStatus">
          <template slot-scope="scope">
            {{ renderOption(scope.row.pushStatus, "pushStatus") }}
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="220px">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="view(scope.row)"
              size="small"
            >
              查看
            </el-button>
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="edit(scope.row)"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="handlerDelete(scope.row)"
              size="small"
            >
              删除
            </el-button>

            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="publish(scope.row)"
              size="small"
              >上架</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 1"
              @click="revokePublish(scope.row)"
              size="small"
              >下架</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.recommend == 2"
              @click="recommended(scope.row)"
              size="small"
              >推荐</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.recommend == 1"
              @click="revokeRecommended(scope.row)"
              size="small"
              >取消推荐</el-button
            >
          </template>
        </el-table-column>
      </edu-table>
    </div>

    <edu-dialog
      :title.sync="dialogConfig.title"
      :visible.sync="dialogConfig.showDialog"
      @close="handleDialogClose"
      width="70%"
      height="650px"
    >
      <el-form
        ref="dialogForm"
        :model="dialogConfig.formData"
        :rules="dialogConfig.action === 'view' ? {} : dialogConfig.rules"
        label-width="230px"
        size="small"
        :disabled="dialogConfig.action === 'view'"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="dialogConfig.formData.title" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="dialogConfig.formData.price"
                controls-position="right"
                :min="0"
                :step="0.01"
                :precision="2"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属品类" prop="catgory">
              <QueryCategoryTree
                v-model="dialogConfig.formData.catgory"
                :url="queryProduceCategoryTree"
                :payload="{}"
                :cascaderProps="{
                  children: 'subProduceCategoryList',
                  label: 'name',
                  value: 'id',
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="农产品类型" prop="produceType">
              <QueryCategoryTree
                v-model="dialogConfig.formData.produceType"
                cacheValue="PRODUCE_TYPE"
                :payload="{ dictType: 'PRODUCE_TYPE' }"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="卖点" prop="resume">
              <el-input
                v-model="dialogConfig.formData.resume"
                :show-word-limit="true"
                :maxlength="20"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务商" prop="providerName">
              <el-input
                v-model="dialogConfig.formData.providerName"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片" prop="image">
              <Upload v-model="dialogConfig.formData.image" ref="uploadComp" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <Editor
                v-model="dialogConfig.formData.description"
                :disabled="dialogConfig.action === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="buttons" v-if="dialogConfig.action !== 'view'">
        <template>
          <el-button @click="closeDialog(dialogConfig)"> 取消 </el-button>
          <el-button type="primary" @click="handlerSubmit"> 提交 </el-button>
        </template>
      </span>
      <span slot="buttons" v-else>
        <template>
          <el-button @click="closeDialog(dialogConfig)">返回</el-button>
        </template>
      </span>
    </edu-dialog>
  </div>
</template>

<script>
import utils from "@/utils";
import mixins from "@/mixins";

import {
  pageFarmProduce,
  detailFarmProduce,
  addFarmProduce,
  updateFarmProduce,
  pushFarmProduce,
  unpushFarmProduce,
  recommendFarmProduce,
  unrecommendFarmProduce,
  deleteFarmProduce,
  exportFarmProduce,
} from "@/api/agricultureProducts";
import { queryProduceCategoryTree } from "@/api/common";

const formData = {
  catgory: "", //所属品类
  produceType: "", //农产品类型
  description: "", //产品详情
  image: "", //图片文件id
  price: null, //价格
  providerName: "", //所属商户名称
  resume: "", //卖点摘要
  title: "", //农产品名称
};
export default {
  mixins: [mixins],
  data() {
    return {
      queryParams: {
        condition: {},
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableList: [],
      dialogConfig: {
        title: "",
        showDialog: false,
        action: "add",
        formData: {},
        rules: {
          title: [
            {
              required: true,
              validator: this.checkTitle,
              trigger: "blur",
            },
          ],
          price: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          resume: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          image: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          catgory: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          produceType: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          providerName: [
            {
              required: true,
              validator: this.checkProviderName,
              trigger: "blur",
            },
          ],
          description: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
        },
      },
      options: {},
      queryProduceCategoryTree,
    };
  },
  created() {
    this.initOptions();
  },
  methods: {
    checkTitle(rule, value, callback) {
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (value.length > 100) {
        callback(new Error("超出字数限制100"));
      } else {
        callback();
      }
    },
    checkProviderName(rule, value, callback) {
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (value.length > 100) {
        callback(new Error("超出字数限制100"));
      } else {
        callback();
      }
    },
    async initOptions() {
      // 查询列表
      this.query();
    },
    // 查询
    async query(pageNum) {
      // 有pageNum 重置为第一页
      if (pageNum) {
        this.queryParams.pageNum = pageNum;
      }

      let { returnObj } = await pageFarmProduce(this.queryParams);
      this.tableList = returnObj.list;
      this.queryParams.total = returnObj.total;
      this.queryParams.pageSize = returnObj.pageSize;
    },
    // 重置
    reset() {
      for (var key in this.queryParams.condition) {
        this.queryParams.condition[key] = "";
      }
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;

      this.query();
    },
    // 分页
    handleCurrentChange(row) {
      this.queryParams.pageSize = row.pageSize;
      this.queryParams.pageNum = row.pageNum;

      this.query();
    },
    closeDialog(dialog) {
      dialog.showDialog = false;
      this.$refs["dialogForm"].resetFields();
    },
    openDialog(dialog) {
      dialog.showDialog = true;
    },
    // 新增
    add() {
      this.dialogConfig.title = "新增";
      this.dialogConfig.action = "add";
      this.dialogConfig.formData = utils.clone(formData);

      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });
    },
    // 修改
    async edit(row) {
      this.dialogConfig.title = "编辑";
      this.dialogConfig.action = "edit";

      let { returnObj } = await detailFarmProduce(row.id);
      this.dialogConfig.formData = utils.clone(returnObj);

      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });
    },
    // 保存提交
    handlerSubmit() {
      let params = {
        ...this.dialogConfig.formData,
        description: this.formatRichText(
          this.dialogConfig.formData.description
        ),
      };

      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if (this.dialogConfig.action == "add") {
            addFarmProduce(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          } else {
            updateFarmProduce(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          }
        }
      });
    },
    // 查看
    async view(row) {
      this.dialogConfig.title = "查看";
      this.dialogConfig.action = "view";
      //  this.dialogConfig.formData = utils.clone(row);
      let { returnObj } = await detailFarmProduce(row.id);
      this.dialogConfig.formData = utils.clone(returnObj);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });
      this.openDialog(this.dialogConfig);
    },
    // 关闭弹框
    handleDialogClose() {
      this.closeDialog(this.dialogConfig);
    },
    // 上架
    async publish(row) {
      this.$confirm(`确认上架?`).then(() => {
        pushFarmProduce([row.id]).then((res) => {
          this.$message({
            type: "success",
            message: "成功",
          });
          this.query();
        });
      });
    },
    // 下架
    async revokePublish(row) {
      unpushFarmProduce([row.id]).then((res) => {
        this.$message({
          type: "success",
          message: "成功",
        });
        this.query();
      });
    },
    // 批量上架
    async batchPublish() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量上架?`).then(() => {
        pushFarmProduce(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量上架成功",
          });
          this.query();
        });
      });
    },
    // 批量下架
    async revokeBatchPublish() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量取消发布?`).then(() => {
        unpushFarmProduce(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量取消发布成功",
          });
          this.query();
        });
      });
    },

    // 推荐
    async recommended(row) {
      this.$confirm(`确认推荐?`).then(() => {
        recommendFarmProduce([row.id]).then((res) => {
          this.$message({
            type: "success",
            message: "成功",
          });
          this.query();
        });
      });
    },
    // 取消推荐
    async revokeRecommended(row) {
      unrecommendFarmProduce([row.id]).then((res) => {
        this.$message({
          type: "success",
          message: "成功",
        });
        this.query();
      });
    },
    // 批量推荐
    async batchRecommended() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量推荐?`).then(() => {
        recommendFarmProduce(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量推荐成功",
          });
          this.query();
        });
      });
    },
    // 批量取消推荐
    async revokeBatchRecommended() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量取消推荐?`).then(() => {
        unrecommendFarmProduce(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量取消推荐成功",
          });
          this.query();
        });
      });
    },
    // 删除
    async handlerDelete(row) {
      let idField = "id";
      if (row && row[idField]) {
        this.batchDelete(deleteFarmProduce, idField, [row[idField]]);
      } else {
        this.batchDelete(deleteFarmProduce, idField);
      }
    },
    // 导出
    onExport() {
      let selectedIds = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      // if (!selectedIds || selectedIds.length == 0) {
      //   this.$message({
      //     type: "warning",
      //     message: "请勾选要导出的数据",
      //   });
      //   return;
      // }
      exportFarmProduce({
        selectedIds,
        condition: {
          ...this.queryParams.condition,
        },
      }).then((res) => {
        utils.downloadFile(res);
      });
    },
    rounding(row, column) {
      return parseFloat(row[column.property]).toFixed(2);
    },
  },
};
</script>

<style lang="scss" scoped></style>
